﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Corina.Commands;
using Corina.Datamodel.Entities;
using System.Linq;
using Corina.Enumerations;
using System.Windows.Media.Imaging;
using System.IO;

namespace Corina.Cydee.Apphub.Viewmodels
{
    public class GuobiaoConfigViewmodel : ViewmodelBase
    {
        private OpenFileDialog dialog = new OpenFileDialog();
        private WebClient imagePreviewClient = new WebClient();

        protected Image PreviewImageControl { get; set; }
        public GuobiaoConfigViewmodel()
        {
            CommonBaseClient.GetAllGuobiaoConfigItemsCompleted += GetAllGuobiaoConfigItemsCompleted;
            DocumentClient.GetAllGuobiaoDocumentItemsCompleted += GetAllGuobiaoDocumentItemsCompleted;
            DocumentClient.GetNationalStandardInfoCompleted+=GetNationalStandardInfoCompleted;
            CommonBaseClient.InsertGuobiaoConfigCompleted += InsertGuobiaoConfigCompleted;
            CommonBaseClient.UpdateGuobiaoConfigCompleted += UpdateGuobiaoConfigCompleted;

            DeviceClient.GetSpecimenKindItemsCompleted += GetSpecimenKindItemsCompleted;

            UploaderClient.AppendToFileCompleted += AppendToFileCompleted;

            imagePreviewClient.OpenReadCompleted+=DownloadPreviewImageCompleted;

            if (DataContext.IsValid)
            {
                DocumentClient.GetAllGuobiaoDocumentItemsAsync(Account, Password, "", 1, 20);
                DeviceClient.GetSpecimenKindItemsAsync();
                LoadData();
            }

            
        }

        private void DownloadPreviewImageCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                BitmapImage image = new BitmapImage();
                image.SetSource(e.Result);
                PreviewImageControl.Source = image;
            }
        }

        private void AppendToFileCompleted(object sender, DataService.AppendToFileCompletedEventArgs e)
        {
            switch (Operation)
            {
                case EntityOperation.Insert:
                    CommonBaseClient.InsertGuobiaoConfigAsync(Account, Password, SpecimenKindId, MeasureName, GuobiaoEntity.Id, StoredFileName + PreviewImageFile.Extension);
                    break;
                case EntityOperation.Update:
                    CommonBaseClient.UpdateGuobiaoConfigAsync(Account, Password, UpdateItemId, GuobiaoEntity.Id, StoredFileName + PreviewImageFile.Extension);
                    break;
                default: break;
            }
        }

        private void GetSpecimenKindItemsCompleted(object sender, DataService.GetSpecimenKindItemsCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                SpecimenKindCollection = new ObservableCollection<SpecimenKindInfo>(e.Result.Entities.OfType<SpecimenKindInfo>());
            }
        }

        public void UILoaded(object sender, EventArgs e)
        {

            Page page = sender as Page;
            PreviewImageControl = (Image)page.FindName("previewImage");
        }

        private void UpdateGuobiaoConfigCompleted(object sender, DataService.UpdateGuobiaoConfigCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result.Result == Enumerations.ResultValue.Succeed)
                {
                    LoadData();
                    Clear();
                }
            }
        }

        private void GetNationalStandardInfoCompleted(object sender, DataService.GetNationalStandardInfoCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result.Result == Enumerations.ResultValue.Succeed)
                {
                    var items = e.Result.Entities.OfType<NationalStandardInfo>();
                    if (items.Count() > 0)
                    {
                        GuobiaoEntity = items.FirstOrDefault();
                    }
                    else
                    {
                        MessageBox.Show("未找到相关信息，请检查输入是否有误！");
                    }
                }
            }
            GettingGuobiao = false;
        }

        private void InsertGuobiaoConfigCompleted(object sender, DataService.InsertGuobiaoConfigCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result.Result == Enumerations.ResultValue.Succeed)
                {
                    LoadData();
                    Clear();
                }
            }
        }

        private void GetAllGuobiaoDocumentItemsCompleted(object sender, DataService.GetAllGuobiaoDocumentItemsCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result.Result == Enumerations.ResultValue.Succeed)
                {
                    var items = (from t in e.Result.DataObjects
                                 select new
                                 {
                                     ItemIndex = t["ROW_NUMBER"],
                                     Id = t["Id"],
                                     Name = t["Name"],
                                     Code = (string)t["Code"]
                                 });
                    GuobiaoCollection = new ObservableCollection<object>(items.OrderBy(t => t.Code));
                }
            }
        }

        private void GetAllGuobiaoConfigItemsCompleted(object sender, DataService.GetAllGuobiaoConfigItemsCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result.Result == ResultValue.Succeed)
                {
                    var items = (from t in e.Result.DataObjects
                                 select new
                                 {
                                     ItemIndex = t["ROW_NUMBER"],
                                     Id = t["Id"],
                                     Name = t["Name"],
                                     GBName = t["GBName"],
                                     Code = t["Code"],
                                     Filename = t["DocumentName"],
                                     SpecimenKind = t["SpecimenKind"],
                                     SpecimenKindId = (int)t["SpecimenKindId"],
                                     PreviewImage = (string)t["PreviewImage"],
                                     HasPreviewImage = !string.IsNullOrEmpty((string)t["PreviewImage"])
                                 });
                    ItemsCollection = new ObservableCollection<object>(items);
                    ItemsCount = e.Result.TotalCount;
                }
            }
            IsBusy = false;
        }

        protected override void LoadData(params object[] paras)
        {
            IsBusy = true;
            CommonBaseClient.GetAllGuobiaoConfigItemsAsync(Account, Password, SearchMeasureName, SearchCode, 0, Index, 20);
        }

        protected override void OperationChanged()
        {
            RaisePropertyChanged(() => MeasureNameReadOnly);
            RaisePropertyChanged(() => ShowUpdate);
        }

        private void Clear()
        {
            Operation = EntityOperation.None;
            PreviewImageFile = null;
            GuobiaoCode = string.Empty;
            MeasureName = string.Empty;
            GuobiaoEntity = null;
            SelectedSpecimenKind = null;
            UpdateItemId = 0;
            BitmapImage bitmapimage = new BitmapImage();
            bitmapimage.UriSource = new Uri("/Corina.Cydee.Apphub;component/Images/Picture.png", UriKind.RelativeOrAbsolute);
            PreviewImageControl.Source = bitmapimage;
            StoredFileName = System.Guid.NewGuid().ToString();
        }

        #region Collection
        private ObservableCollection<object> _itemsCollection;
        public ObservableCollection<object> ItemsCollection
        {
            get { return _itemsCollection; }
            set
            {
                _itemsCollection = value;
                RaisePropertyChanged(() => ItemsCollection);
            }
        }

        private ObservableCollection<object> _guobiaoCollection;
        public ObservableCollection<object> GuobiaoCollection
        {
            get { return _guobiaoCollection; }
            set {
                _guobiaoCollection = value;
                RaisePropertyChanged(() => GuobiaoCollection);
            }
        }

        private ObservableCollection<SpecimenKindInfo> _specimenKindCollection;
        public ObservableCollection<SpecimenKindInfo> SpecimenKindCollection
        {
            get { return _specimenKindCollection; }
            set {
                _specimenKindCollection = value;
                RaisePropertyChanged(() => SpecimenKindCollection);
            }
        }
        #endregion

        #region Update
        private string _measureName;
        public string MeasureName
        {
            get { return _measureName; }
            set {
                _measureName = value;
                RaisePropertyChanged(() => MeasureName);
                RaisePropertyChanged(() => SubmitCommand);
            }
        }

        private string _guobiaoCode;
        public string GuobiaoCode
        {
            get { return _guobiaoCode; }
            set {
                _guobiaoCode = value;
                RaisePropertyChanged(() => GuobiaoCode);
                RaisePropertyChanged(() => GetGuobiaoCommand);
            }
        }

        private NationalStandardInfo _guobiaoEntity;
        public NationalStandardInfo GuobiaoEntity
        {
            get { return _guobiaoEntity; }
            set
            {
                _guobiaoEntity = value;
                RaisePropertyChanged(() => GuobiaoEntity);
                RaisePropertyChanged(() => SubmitCommand);
            }
        }

        private bool _gettingGuobiao = false;
        public bool GettingGuobiao
        {
            get { return _gettingGuobiao; }
            set {
                _gettingGuobiao = value;
                RaisePropertyChanged(() => GettingGuobiao);
            }
        }

        public bool MeasureNameReadOnly
        {
            get { return Operation != EntityOperation.Insert; }
        }

        private FileInfo _previewImageFile;
        public FileInfo PreviewImageFile
        {
            get { return _previewImageFile; }
            set {
                _previewImageFile = value;
                RaisePropertyChanged(() => PreviewImageFile);
            }
        }

        private SpecimenKindInfo _selectedSpecimenKind;
        public SpecimenKindInfo SelectedSpecimenKind
        {
            get { return _selectedSpecimenKind; }
            set {
                _selectedSpecimenKind = value;
                RaisePropertyChanged(() => SelectedSpecimenKind);
            }
        }

        public int SpecimenKindId
        {
            get { return SelectedSpecimenKind == null ? 0 : SelectedSpecimenKind.Id; }
        }

        private int _updateItemId = 0;
        public int UpdateItemId
        {
            get { return _updateItemId; }
            set {
                _updateItemId = value;
                RaisePropertyChanged(() => UpdateItemId);
            }
        }
        #endregion

        #region Search
        private string _searchMeasureName = string.Empty;
        public string SearchMeasureName
        {
            get { return _searchMeasureName; }
            set {
                _searchMeasureName = value;
                RaisePropertyChanged(() => SearchMeasureName);
            }
        }

        private string _searchCode = string.Empty;
        public string SearchCode
        {
            get { return _searchCode; }
            set
            {
                _searchCode = value;
                RaisePropertyChanged(() => SearchCode);
            }
        }
        #endregion

        #region Upload
        private string _storedFileName = System.Guid.NewGuid().ToString();
        public string StoredFileName
        {
            get { return PreviewImageFile == null ? "" : _storedFileName; }
            set
            {
                _storedFileName = value;
                RaisePropertyChanged(() => StoredFileName);
            }
        }

        #endregion

        #region Commands
        public ICommand InsertCommand
        {
            get {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate {
                        Operation = Enumerations.EntityOperation.Insert;
                    }
                };
            }
        }

        public ICommand LoadCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate {
                        Index = 1;
                        LoadData();
                    }
                };
            }
        }

        public ICommand CancelCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        Clear();
                    }
                };
            }
        }

        public ICommand GetGuobiaoCommand {
            get {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return !string.IsNullOrEmpty(GuobiaoCode); },
                    ExecuteCallback = delegate
                    {
                        GettingGuobiao = true;
                        DocumentClient.GetNationalStandardInfoAsync(Account, Password, GuobiaoCode);
                    }
                };
            }
        }

        public ICommand SubmitCommand
        {
            get {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return !string.IsNullOrEmpty(MeasureName) && GuobiaoEntity != null; },
                    ExecuteCallback = delegate
                    {
                        if (PreviewImageFile!=null)
                        {
                            byte[] buffer = new byte[PreviewImageFile.Length];

                            Stream stream = PreviewImageFile.OpenRead();

                            stream.Read(buffer, 0, buffer.Length);

                            UploaderClient.AppendToFileAsync(StoredFileName + PreviewImageFile.Extension, "PreviewImage", true, true, Convert.ToBase64String(buffer));
                        }
                        else
                        {
                            switch (Operation)
                            {
                                case EntityOperation.Insert:
                                    CommonBaseClient.InsertGuobiaoConfigAsync(Account, Password, SpecimenKindId, MeasureName, GuobiaoEntity.Id, "");
                                    break;
                                case EntityOperation.Update:
                                    CommonBaseClient.UpdateGuobiaoConfigAsync(Account, Password, UpdateItemId, GuobiaoEntity.Id, "");
                                    break;
                                default: break;
                            }
                        }
                    }
                };
            }
        }

        public ICommand UpdateCommand
        {
            get {
                return new DelegateCommand(t =>
                {
                    UpdateItemId = (int)GetObjectPropertyValue(t, "Id");
                    MeasureName = (string)GetObjectPropertyValue(t, "Name");
                    GuobiaoCode = (string)GetObjectPropertyValue(t, "Code");
                    int selectedSpecimenKindId = (int)GetObjectPropertyValue(t, "SpecimenKindId");
                    SelectedSpecimenKind = SpecimenKindCollection.FirstOrDefault(i => i.Id == selectedSpecimenKindId);
                    string previewImage = (string)GetObjectPropertyValue(t, "PreviewImage");
                    if (!string.IsNullOrEmpty(previewImage))
                    {
                        string url = string.Format("{0}LoadFile.aspx?f=PreviewImage&n={1}", WebServiceAddress, previewImage);
                        
                        Uri imageUri = new Uri(url);
                        imagePreviewClient.OpenReadAsync(imageUri);
                    }
                    Operation = EntityOperation.Update;
                    //RaisePropertyChanged(() => MeasureNameReadOnly);
                });
            }
        }

        public ICommand OpenFileCommand
        {
            get {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        if (dialog.ShowDialog() == true)
                        {
                            PreviewImageFile = dialog.File;
                            BitmapImage image = new BitmapImage();
                            image.SetSource(PreviewImageFile.OpenRead());
                            PreviewImageControl.Source = image;
                        }
                    }
                };
            }
        }
        #endregion
    }
}
